package com.woniuxy.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	
	@RequestMapping("/login")
	@ResponseBody
	public ResponseEntity<Void> login(@RequestBody User user) {
		ResponseEntity<Void> re = new ResponseEntity<>();
		//获取subject
		Subject su = SecurityUtils.getSubject();
		//判断有没有认证
		if(!su.isAuthenticated()) {
			//没有认证就登录验证
//			String pwd = new SimpleHash("MD5",user.getPwd(),user.getUname(),100).toString();
			UsernamePasswordToken token = new UsernamePasswordToken(user.getUname(),user.getPwd());
			try {
				su.login(token);
				System.out.println("登陆成功");
				re.setCode(1);
			} catch (UnknownAccountException e) {
				System.out.println("账号不存在");
				re.setCode(ResponseEntity.FAIL);
				re.setMsg("账号不存在");
			}catch (IncorrectCredentialsException e) {
				System.out.println("密码错误");
				re.setCode(ResponseEntity.FAIL);
				re.setMsg("密码错误");
			}catch (AuthenticationException e) {
				System.out.println("登录异常");
				System.out.println(e);
				re.setCode(ResponseEntity.FAIL);
				re.setMsg("登录异常");
			}
		}
		
		return re;
	}
}
